package com.df.tv.launcher.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.df.tv.launcher.R;
import com.df.tv.launcher.adapter.SettingAdapter;
import com.df.tv.launcher.entity.SettingBean;
import com.df.tv.launcher.params.ComParams;
import com.df.tv.launcher.util.NetworkStatus;
import com.df.tv.launcher.view.DialogGenerator;
import com.telecom.tv189.comlib.util.Log;

/**
 * Show system setting interface
 * 
 * @author liubaolin
 */
public class SettingFragment extends Fragment implements OnItemClickListener, OnItemSelectedListener,
        OnFocusChangeListener {
    private String TAG = "SettingFragment";
    private GridView mSettingGridView;
    private SettingAdapter mSettingAdapter;
    private RelativeLayout mFocusLayout;
    private ImageView mFocusImageView;
    private TextView mFocusTxtView;

    private TextView mNetIP;
    private TextView mNetType;
    private NetWorkBroadCastReceiver mNetReceiver;
    private SettingBean mSettingBeanForUSB;
    private List<SettingBean> mSettingList = new ArrayList<SettingBean>();
    private static final int SET_FIRST_ITEM_SELECTED_FOR_GRIDVIEW = 0x00;
    private static final int USB_STATE_ON = 0x01;
    private static final int USB_STATE_OFF = 0x02;
    private static final int SET_NETWORK_STATE_ON = 0x03;
    private static final int SET_NETWORK_STATE_OFF = 0x04;

    private Context mContext;
    private DialogGenerator mDialogDenerator;
    private boolean isSettingFragment = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "-->onCreate");
        super.onCreate(savedInstanceState);
        //		registerReceiver();
        mDialogDenerator = new DialogGenerator(mContext);//USB检测Dialog提示框
        mSettingList = SettingBean.getSettingItems(mContext);//获取数据,填充GridView适配器
        this.addOrDecUsbBeanInfo();//添加或删除USB信息
        this.registerNetReceiver();//注册网络监听的服务
        isSettingFragment = true;
    }

    /**
     * 从其他页面跳转到设置页面时,根据是否挂载了USB来增加GridView的Item
     */
    private void addOrDecUsbBeanInfo() {
        if (mSettingBeanForUSB == null) {
            mSettingBeanForUSB = new SettingBean("USB", R.drawable.setting10, ComParams.USB_OPERATION_ACTION);
        }
        if (MainFrameFragment.isUsbConnecting) {//当前USB挂载上
            if (mSettingList != null && !mSettingList.contains(mSettingBeanForUSB)) {//类集中不包含USB信息
                mSettingList.add(mSettingBeanForUSB);
            }
        }
        else {//当前USB未挂载上
            if (mSettingList != null && mSettingList.contains(mSettingBeanForUSB)) {//类集中包含USB信息
                mSettingList.remove(mSettingBeanForUSB);
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        Log.d(TAG, "-->onAttach");
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "-->onCreateView");
        View view = (RelativeLayout) inflater.inflate(R.layout.setting, container, false);
        mSettingGridView = (GridView) view.findViewById(R.id.gv_setting_item);
        mFocusLayout = (RelativeLayout) view.findViewById(R.id.rlyt_focus);//聚焦时放大控件的布局
        mFocusImageView = (ImageView) view.findViewById(R.id.img_setting_item);//聚焦时放大显示图片的控件
        mFocusTxtView = (TextView) view.findViewById(R.id.tv_title);//聚焦时放大显示文字的控件

        mNetIP = (TextView) view.findViewById(R.id.tv_net_ip);
        mNetType = (TextView) view.findViewById(R.id.tv_net_type);

        mSettingAdapter = new SettingAdapter(mContext, mSettingList);
        mSettingGridView.setAdapter(mSettingAdapter);
        mSettingGridView.setOnItemClickListener(this);
        mSettingGridView.setOnItemSelectedListener(this);
        mSettingGridView.setOnFocusChangeListener(this);
        return view;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "-->onItemSelected");
        mFocusTxtView.setText(mSettingList.get(position).getName());
        mFocusImageView.setBackgroundResource(mSettingList.get(position).getResId());
        mFocusLayout.setX(view.getX() + parent.getX() + view.getWidth() / 2 - mFocusLayout.getWidth() / 2);
        mFocusLayout.setY(view.getY() + parent.getY() + view.getHeight() / 2 - mFocusLayout.getHeight() / 2);
        //		mFocusLayout.setFocusable(true);
        mFocusLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        mFocusLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "-->onItemClick");
        //		Intent intent = new Intent();
        //		intent.setAction(mSettingList.get(position).getAction());
        //		startActivity(intent);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "-->onResume");
        super.onResume();
        if (isSettingFragment) {
            mHandler.sendEmptyMessage(SET_FIRST_ITEM_SELECTED_FOR_GRIDVIEW);
        }
        updateNetworkState();
    }

    @Override
    public void onPause() {
        Log.d(TAG, "-->onPause");
        super.onPause();
        isSettingFragment = false;
    }

    @Override
    public void onStop() {
        Log.d(TAG, "-->onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "-->onDestroy");
        super.onDestroy();

        isSettingFragment = false;
        if (mDialogDenerator != null && mDialogDenerator.isShowing()) {
            mDialogDenerator.dismiss();
            mDialogDenerator = null;
        }

        if (mNetReceiver != null) {
            mContext.unregisterReceiver(mNetReceiver);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            mSettingGridView.setSelection(-1);
        }
    }

    /**
     * Register netWork receiver动态注册广播,当前Activity关掉后失效
     */
    private void registerNetReceiver() {
        mNetReceiver = new NetWorkBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(mNetReceiver, filter);
    }

    private void updateNetworkState() {
        ConnectivityManager manager = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null) {
            mHandler.sendEmptyMessage(SET_NETWORK_STATE_ON);
        }
        else {
            mHandler.sendEmptyMessage(SET_NETWORK_STATE_OFF);
        }
    }

    /**
     * YinRH 监听到网络的广播
     * 
     * @author
     * 
     */
    private class NetWorkBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                updateNetworkState();
            }
        }
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case SET_FIRST_ITEM_SELECTED_FOR_GRIDVIEW:
                mFocusTxtView.setText(mSettingList.get(0).getName());
                mFocusImageView.setBackgroundResource(mSettingList.get(0).getResId());
                mFocusLayout.setX(mSettingGridView.getChildAt(0).getX() + mSettingGridView.getX()
                        + mSettingGridView.getChildAt(0).getWidth() / 2 - mFocusLayout.getWidth() / 2);
                mFocusLayout.setY(mSettingGridView.getChildAt(0).getY() + mSettingGridView.getY()
                        + mSettingGridView.getChildAt(0).getHeight() / 2 - mFocusLayout.getHeight() / 2);
                mSettingGridView.setFocusable(true);
                mSettingGridView.requestFocus();
                mFocusLayout.setVisibility(View.VISIBLE);
                break;
            case USB_STATE_ON:
                mFocusLayout.setVisibility(View.INVISIBLE);
                //mSettingBeanForUSB = new SettingBean("USB", R.drawable.setting10, ComParams.USB_OPERATION_ACTION);
                //mSettingList.add(mSettingBeanForUSB);
                SettingFragment.this.addOrDecUsbBeanInfo();//添加或删除USB信息
                mSettingAdapter.notifyDataSetChanged();
                mDialogDenerator.createUsbDetectedDialog();
                break;
            case USB_STATE_OFF:
                if (mDialogDenerator.isShowing()) {
                    mDialogDenerator.dismiss();
                }
                mFocusLayout.setVisibility(View.INVISIBLE);
                SettingFragment.this.addOrDecUsbBeanInfo();//添加或删除USB信息
                //mSettingList.remove(mSettingBeanForUSB);
                mSettingAdapter.notifyDataSetChanged();
                break;

            case SET_NETWORK_STATE_ON:
                boolean isWifi = NetworkStatus.getInstance().isWiFiActive(mContext);//判断网络类型
                String ipAddress = NetworkStatus.getInstance().getIpAddress(isWifi ? "wlan0" : "eth0");
                String netState = mContext.getString(isWifi ? R.string.network_wireless : R.string.network_wired);
                mNetIP.setText(" " + ipAddress);
                mNetType.setText(" ( " + netState + " )");
                break;

            case SET_NETWORK_STATE_OFF:
                mNetIP.setText(" " + mContext.getString(R.string.network_idle));
                mNetType.setText("");
                break;
            default:
                break;
            }
        };
    };

}
